// static/js/schedule_detail.js

;(function(){
  document.addEventListener('DOMContentLoaded', () => {
    // Elements
    const container       = document.getElementById('cards-container');
    const detailModalEl   = document.getElementById('scheduleDetailModal');
    const detailModal     = new bootstrap.Modal(detailModalEl);
    const detailError     = document.getElementById('detailErrorMsg');
    const deleteBtn       = document.getElementById('detail-delete');
    const deleteOptions   = document.getElementById('delete-options');
    const optOnceDelete   = document.getElementById('opt-once');
    const optOngoingDel   = document.getElementById('opt-ongoing');
    const modifyBtn       = document.getElementById('detail-modify');
    const modifyOptions   = document.getElementById('modify-options');
    const optOnceMod      = document.getElementById('opt-modify-once');
    const optOngoingMod   = document.getElementById('opt-modify-ongoing');
    const confirmModalEl  = document.getElementById('confirmModal');
    const confirmModal    = new bootstrap.Modal(confirmModalEl);
    const confirmMsgEl    = document.getElementById('confirmMessage');
    const confirmOkBtn    = document.getElementById('confirmOk');

    let currentId      = null;
    let pendingAction  = null;

    // Utility: hide both delete & modify options
    function hideAllOptions() {
      deleteOptions.style.display = 'none';
      modifyOptions.style.display = 'none';
    }

    // When detail modal opens: hide options & errors
    detailModalEl.addEventListener('show.bs.modal', () => {
      hideAllOptions();
      detailError.style.display = 'none';
    });

    // Clicking anywhere hides both panels
    document.addEventListener('click', () => {
      hideAllOptions();
    });

    // Fetch and show details when clicking a card (excluding status button)
    container.addEventListener('click', async e => {
      const card = e.target.closest('.schedule-card');
      if (!card || e.target.closest('.btn-status')) return;
      const btnStatus = card.querySelector('.btn-status');
      currentId = btnStatus.getAttribute('data-id');

      try {
        const res = await fetch(`/api/schedules/${currentId}`);
        if (!res.ok) throw new Error(res.status);
        const data = await res.json();
        // Save globally for modify module
        window.currentData = data;

        // Populate detail fields
        document.getElementById('detail-student').textContent = data.student_name;
        document.getElementById('detail-course').textContent  = data.course;
        document.getElementById('detail-school').textContent  = data.school;
        document.getElementById('detail-grade').textContent   = data.grade;
        document.getElementById('detail-address').textContent = data.address;
        document.getElementById('detail-fee').textContent     = data.fee;
        document.getElementById('detail-status').textContent  = data.status;
        document.getElementById('detail-date').textContent    = data.date;
        document.getElementById('detail-start').textContent   = data.start_time;
        document.getElementById('detail-end').textContent     = data.end_time;
        document.getElementById('detail-remark').textContent  = data.remark || '—';

        detailModal.show();
      } catch (err) {
        console.error('加载详情失败', err);
      }
    });

    // DELETE options toggle
    deleteBtn.addEventListener('click', e => {
      e.stopPropagation();
      hideAllOptions();
      deleteOptions.style.display = deleteOptions.style.display === 'flex' ? 'none' : 'flex';
    });
    deleteOptions.addEventListener('click', e => e.stopPropagation());

    // MODIFY options toggle
    modifyBtn.addEventListener('click', e => {
      e.stopPropagation();
      hideAllOptions();
      modifyOptions.style.display = modifyOptions.style.display === 'flex' ? 'none' : 'flex';
    });
    modifyOptions.addEventListener('click', e => e.stopPropagation());

    // Common delete executor
    function doDelete(url) {
      fetch(url, { method: 'DELETE' })
        .then(res => {
          if (!res.ok) throw new Error(res.status);
          detailModal.hide();
          if (typeof loadCards === 'function') loadCards();
        })
        .catch(err => {
          detailError.textContent = '删除失败：' + err.message;
          detailError.style.display = 'inline';
          setTimeout(() => detailError.style.display = 'none', 3000);
        });
    }

    // DELETE: 本次
    optOnceDelete.addEventListener('click', () => {
      deleteOptions.style.display = 'none';
      if (window.currentData.status !== '未上') {
        detailError.textContent = '该排课已完成，无法删除本次。';
        detailError.style.display = 'inline';
        setTimeout(() => detailError.style.display = 'none', 3000);
        return;
      }
      confirmMsgEl.textContent = '确定要删除本次排课吗？';
      pendingAction = () => doDelete(`/api/schedules/${currentId}`);
      confirmModal.show();
    });

    // DELETE: 本次及后续
    optOngoingDel.addEventListener('click', () => {
      deleteOptions.style.display = 'none';
      if (window.currentData.status !== '未上') {
        detailError.textContent = '该排课已完成，无法删除本次及后续。';
        detailError.style.display = 'inline';
        setTimeout(() => detailError.style.display = 'none', 3000);
        return;
      }
      confirmMsgEl.textContent = '确定要删除本次及后续所有排课吗？';
      pendingAction = () => doDelete(`/api/schedules/${currentId}/ongoing`);
      confirmModal.show();
    });

    // Confirm modal OK
    confirmOkBtn.addEventListener('click', () => {
      confirmModal.hide();
      if (typeof pendingAction === 'function') pendingAction();
    });

    // MODIFY: 本次
    optOnceMod.addEventListener('click', () => {
      modifyOptions.style.display = 'none';
      if (window.currentData.status === '已上') {
        detailError.textContent = '该排课已完成，无法修改本次。';
        detailError.style.display = 'inline';
        setTimeout(() => detailError.style.display = 'none', 3000);
        return;
      }
      // Trigger modify-once workflow
      window.dispatchEvent(new CustomEvent('modify-once'));
    });

    // MODIFY: 本次及后续
    optOngoingMod.addEventListener('click', () => {
      modifyOptions.style.display = 'none';
      if (window.currentData.status === '已上') {
        detailError.textContent = '该排课已完成，无法修改本次及后续。';
        detailError.style.display = 'inline';
        setTimeout(() => detailError.style.display = 'none', 3000);
        return;
      }
      // Trigger modify-ongoing workflow
      window.dispatchEvent(new CustomEvent('modify-ongoing'));
    });
  });
})();
